﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using LDSP.BRL;
using BYFW.SFL;
using BYFW.BOL;
using BYFW.DAL;
using System.Data;
using System.Diagnostics;

namespace LDSP.Helper
{
    public class TreeNodeModifier
    {
        IDictionary<TreeNode, int> _commonNodesNumberDic = new Dictionary<TreeNode, int>();//枝节点的统计数据。
        IDictionary<int, IList<TreeNode>> _nodesByLevel = new Dictionary<int, IList<TreeNode>>();

        protected int _enterpriseID;
        protected DocType _docType;
        protected IDictionary<int, int> _codByCatalogDic = new Dictionary<int, int>(); //直属每个节点自己的统计数据。

        public TreeNodeModifier(int enterpriseID, DocType docType)
        {
            _enterpriseID = enterpriseID;
            _docType = docType;
        }

        /// <summary>
        /// 计算节点对应的法规个数。
        /// </summary>
        /// <param name="root"></param>
        public void CaculateNumber(TreeNode root, string cond)
        {
            //初始化catalog里的直属节点个数。
            InitializeCodByCatalog(cond);

            //按level归类节点。
            InitializeNodesByLevel(root);

            //从叶子节点往上，逐层计算枝节点的累计个数（不含直属节点个数）。
            CaculateByLevel();

            //更新树上的信息。
            UpdateTree(root);
        }

        protected virtual void InitializeCodByCatalog(string cond)
        {

        }

        private void InitializeNodesByLevel(TreeNode root)
        {
            if (!_nodesByLevel.ContainsKey(root.Depth))
            {
                IList<TreeNode> nodes = new List<TreeNode>();
                _nodesByLevel.Add(root.Depth, nodes);
            }

            //将当前节点加到字典里。
            _nodesByLevel[root.Depth].Add(root);

            //递归遍历子节点。
            if (root.ChildNodes.Count > 0)
            {
                foreach (TreeNode node in root.ChildNodes)
                {
                    InitializeNodesByLevel(node);
                }
            }
        }

        private void CaculateByLevel()
        {
            int depth = _nodesByLevel.Keys.Count - 1;

            for (int i = depth; i > 0; i--)
            {
                foreach (TreeNode node in _nodesByLevel[i])
                {
                    //获取累计值。
                    int cumulative = _commonNodesNumberDic.ContainsKey(node) ? _commonNodesNumberDic[node] : 0;

                    //加上自己直属节点值。
                    cumulative += CaculateDirectCodNumber(node);

                    //将结果更新给上级节点。
                    if (node.Parent != null)
                    {
                        if (!_commonNodesNumberDic.ContainsKey(node.Parent))
                        {
                            _commonNodesNumberDic.Add(node.Parent, 0);
                        }

                        _commonNodesNumberDic[node.Parent] += cumulative;
                    }
                }
            }
        }

        /// <summary>
        /// 递归更新树。
        /// </summary>
        /// <param name="root"></param>
        private void UpdateTree(TreeNode root)
        {
            int total = CombineSubAndSelf(root);
            root.Text = GetTextFromValue(root) + " (" + total.ToString() + ") ";

            foreach (TreeNode node in root.ChildNodes)
            {
                if (node.ChildNodes.Count > 0)
                {
                    UpdateTree(node);
                }
                else
                {
                    node.Text = GetTextFromValue(node) + " (" + CombineSubAndSelf(node).ToString() + ") ";
                }
            }
        }

        private int CaculateDirectCodNumber(TreeNode node)
        {
            int cumulative = 0;

            int catalogID = UIHelper.GetTreeNodeIDFromValue(node);
            cumulative += _codByCatalogDic.ContainsKey(catalogID) ? _codByCatalogDic[catalogID] : 0;

            return cumulative;
        }

        private int CombineSubAndSelf(TreeNode node)
        {
            int total = 0;

            //直属节点数量
            total += CaculateDirectCodNumber(node);

            //累计值
            total += _commonNodesNumberDic.ContainsKey(node) == true ? _commonNodesNumberDic[node] : 0;

            return total;
        }

        private string GetTextFromValue(TreeNode node)
        {
            string tmp = node.Value;
            int index = tmp.IndexOf(";");
            if (index > -1)
            {
                tmp = tmp.Substring(index + 1);
            }
            return tmp;
        }

        protected IDBOP GetDefaultDB()
        {
            return new BaseEntity().DB;
        }

        protected string AppendCondition(string originCond, string appendCond, bool isAnd)
        {
            return originCond == "" ? appendCond : ("(" + originCond + (isAnd ? " and " : " or ") + appendCond + ")");
        }
    }
}